package com.atlin.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.atlin.model.UserInfo;
import com.atlin.nrpc.core.model.RpcRequest;
import com.atlin.nrpc.core.model.RpcResponse;
import com.atlin.nrpc.core.serializer.JdkSerializer;
import com.atlin.service.UserInfoService;

import java.io.IOException;

/**
 * 静态代理实现
 */
@Deprecated
public class UserInfoServiceProxy implements UserInfoService {

    @Override
    public UserInfo queryUserInfo(UserInfo userInfo) {
        JdkSerializer serializer = new JdkSerializer();

        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserInfoService.class.getName())
                .methodName("queryUserInfo")
                .parameterTypes(new Class[]{UserInfo.class})
                .args(new Object[]{userInfo})
                .build();

        try {
            byte[] bodyBytes = serializer.serialize(rpcRequest);
            byte[] result;
            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080/rpc")
                    .body(bodyBytes)
                    .execute()) {
                result = httpResponse.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (UserInfo) rpcResponse.getData();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
